package com.permission.controller;

import com.permission.model.PerRole;
import com.permission.model.PerUser;
import com.permission.model.PerUserRole;
import com.permission.service.PerRoleService;
import com.permission.service.PerUserRoleService;
import com.permission.service.PerUserService;
import com.permission.util.BizConstants;
import com.solution.framework.controller.BaseController;
import com.solution.framework.util.*;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with generator tools.
 * User: sunguangzhu
 * DateTime:2014-04-28 04:08:30
 */

@Controller
public class PerUserRoleController extends BaseController<PerUserRole> {

    private static final String path_index = "perUserRole/perUserRole_index";
    private static final String path_input = "perUserRole/perUserRole_input";
    private static final String path_view = "perUserRole/perUserRole_view";
    private static final String path_search = "perUserRole/perUserRole_search";

    @Resource
    private PerUserRoleService perUserRoleService;
    @Resource
    private PerRoleService perRoleService;
    @Resource
    private PerUserService perUserService;

    @RequestMapping
    public String index(Long bizId, Model model, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("index method ....");
        model.addAttribute("perUserId", bizId);
        return path_index;
    }

    @ResponseBody
    @RequestMapping
    protected void getGridData(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Criterion> criterions = new ArrayList<Criterion>();
        List<PerRole> perRoles = new ArrayList<PerRole>();
        int total = 0;
        String type = RequestVarsUtil.getString(request, "type");
        Long perUserId = RequestVarsUtil.getLong(request, "perUserId");
        if ("1".equals(type)) {
            perRoles = this.perRoleService.getAvaliblePerRoles(perUserId);
            ResultDto<List<PerRole>> resultDto = new ResultDto<List<PerRole>>(perRoles, total);
            super.writeToClient(response, resultDto.toString());
        }
        if ("2".equals(type)) {
            criterions.add(Restrictions.eq("perUser.id", perUserId));
            Pagination pagination = RequestVarsUtil.getPagination(request);
            List<PerUserRole> entitys = this.perUserRoleService.listByCriteria(pagination, criterions);
            perRoles = this.perRoleService.listByHql();
            List<PerRole> perRolesTemp = new ArrayList<PerRole>(perRoles);
            for (PerRole perRole : perRoles) {
                for (PerUserRole entity : entitys) {
                    if(entity.getPerRole().getId() == perRole.getId()){
                        perRolesTemp.remove(perRole);
                        break;
                    }
                }
            }
            total = perRolesTemp.size();
            ResultDto<List<PerRole>> resultDto = new ResultDto<List<PerRole>>(perRolesTemp, total);
            super.writeToClient(response, resultDto.toString());
        }

    }

    @RequestMapping
    public String edit(Long id, Model model, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("edit method ....");
        PerUserRole perUserRole = this.perUserRoleService.get(id);
        model.addAttribute("perUserRole", perUserRole);
        return path_input;
    }

    @RequestMapping
    public String add(Long bizId, Model model, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("add method ....");
        PerUserRole perUserRole = new PerUserRole();
        model.addAttribute("perUserRole", perUserRole);
        return path_input;
    }

    @RequestMapping
    public String view(Long id, Model model, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("view method ....");
        PerUserRole perUserRole = this.perUserRoleService.get(id);
        model.addAttribute("perUserRole", perUserRole);
        return path_view;
    }

    @RequestMapping
    public String search(Model model, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("search method ....");
        return path_search;
    }

    @ResponseBody
    @RequestMapping
    @DateTimeFormat
    public void save(PerUserRole perUserRole, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        System.out.println("save method ....");
        MessageDto messageDto = new MessageDto();
        try {
            if (perUserRole.getId() != null) {
                this.perUserRoleService.update(perUserRole);
                super.setMessageDto(messageDto, MessageDefined.update_success_info);
            } else {
                this.perUserRoleService.save(perUserRole);
                super.setMessageDto(messageDto, MessageDefined.save_success_info);
            }
        } catch (Exception e) {
            messageDto.setSuccess(false);
            super.setMessageDto(messageDto, MessageDefined.sys_error_info);
            e.printStackTrace();
        }
        super.writeToClient(response, messageDto.toString());
    }

    @ResponseBody
    @RequestMapping
    protected void delete(String ids, HttpServletRequest request, HttpServletResponse response) throws IOException {
        MessageDto messageDto = new MessageDto();
        try {
            this.perUserRoleService.delete(ids);
            super.setMessageDto(messageDto, MessageDefined.del_success_info);
        } catch (Exception e) {
            messageDto.setSuccess(false);
            super.setMessageDto(messageDto, MessageDefined.sys_error_info);
            e.printStackTrace();
        }
        super.writeToClient(response, messageDto.toString());
    }

    @ResponseBody
    @RequestMapping
    protected void savePerUserRole(String ids, Long perUserId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        MessageDto messageDto = new MessageDto();
        try {
            String[] perRoleIds = ids.split(",");
            List<Long> idList = new ArrayList<Long>();
            for (String perRoleId : perRoleIds) {
                idList.add(Long.valueOf(perRoleId));
            }
            PerUser perUser = this.perUserService.get(perUserId);
            List<PerRole> perRoles = this.perRoleService.listByCriteria(Restrictions.in("id", idList));
            for (PerRole perRole : perRoles) {
                PerUserRole perUserRole = new PerUserRole();
                perUserRole.setPerRole(perRole);
                perUserRole.setPerUser(perUser);
                this.perUserRoleService.save(perUserRole);
            }
            super.setMessageDto(messageDto, MessageDefined.save_success_info);
        } catch (Exception e) {
            messageDto.setSuccess(false);
            super.setMessageDto(messageDto, MessageDefined.sys_error_info);
            e.printStackTrace();
        }
        super.writeToClient(response, messageDto.toString());
    }

}
